<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="visible"
      width="500px"
      append-to-body
      :before-close="close"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="名称" prop="lesseeSourceName">
          <el-input
            v-model="form.lesseeSourceName"
            placeholder="请输入来源名称"
            style="width: 240px"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addLesseeSource, updateLesseeSource} from '@/api/contract/lesseeSource'
import { debounce } from '@/utils'

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    title: {
      default: '新增模板'
    },
    data: {
      default: () => ({})
    }
  },
  dicts: ['template_type'],
  data() {
    return {
      visible: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        lesseeSourceName: [
          { required: true, message: '请输入来源名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ] // 来源名称
      }
    }
  },
  watch: {
    value(newVal, oldVal) {
      this.visible = newVal // 监测value的变化，并赋值。
      if (newVal) {
        this.init()
      }
    },
    visible(val) {
      this.$emit('input', val) // 此处监测showMask目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
    }
  },
  methods: {
    init(){
      this.reset()
    },
    //重置表单
    reset() {
      this.form = {
        lesseeSourceName: '',//来源名称
        lesseeSourceId: undefined, //来源id
      }
      this.resetForm('form')
      if(this.data.lesseeSourceId){
        this.form = this.data
      }
    },
    /** 提交按钮 */
    submitForm: debounce(function() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.lesseeSourceId != undefined) {
            updateLesseeSource(this.form).then((response) => {
              this.$modal.msgSuccess(response.msg)
              this.$emit('success')
            })
          } else {
            addLesseeSource(this.form).then((response) => {
              this.$modal.msgSuccess(response.msg)
              this.$emit('success')
            })
          }
          this.close()
        }
      })
    }, 300, true),
    close() {
      this.reset()
      this.visible = false
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  max-height: 80vh !important;
  overflow-y: auto;
}

</style>
